﻿using Bogus;
using Dapper;
using Dapper.Abstractions;
using Dapper.Bulk;

namespace DataAccess.Api.Endpoints.Blog;

public class Synchronize : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        // 批量同步示例
        app.MapPost("/api/blogs/bulk-synchronize", async (IDbConnectionFactory dbConnectionFactory) =>
        {
            using var connection = await dbConnectionFactory.CreateConnectionAsync();

            // 获取当前博客ID的状态
            const string selectIdsSql = "SELECT id FROM blogs LIMIT 100";
            var currentIds = (await connection.QueryAsync<int>(selectIdsSql)).ToList();

            // 创建一个包含现有和新博客的期望状态
            var desiredState = new List<Models.Blog>();

            // 保留70%的现有博客
            var idsToKeep = currentIds.Take((int)(currentIds.Count * 0.7)).ToList();

            foreach (var id in idsToKeep)
            {
                desiredState.Add(new Models.Blog
                {
                    Id = id,
                    Url = new Faker().Internet.Url()
                });
            }

            // 添加一些新博客
            var newBlogs = new Faker<Models.Blog>()
                .RuleFor(p => p.Url, f => f.Internet.Url())
                .Generate(30);

            desiredState.AddRange(newBlogs);

            // 配置实体映射
            BulkManager.Entity<Models.Blog>()
                .Table("blogs")
                .Identity(x => x.Id)
                .UseBulkOptions(options =>
                {
	                options.BatchSize = 1000;
                });

            // 对于同步，我们需要指定匹配的键
            await connection.BulkSynchronizeAsync(desiredState);
            return Results.Ok($"Successfully synchronized blogs database to have exactly {desiredState.Count} blogs");
        })
        .WithName("SynchronizeBlogs")
        .WithTags(Tags.Blog);
    }
}
